package com.czy.owner.ui.wheel;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.WheelListAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.SpecialGoodsAttrModel;
import com.czy.owner.entity.SpecialGoodsModel;
import com.czy.owner.entity.WheelAttrKeyVal;
import com.czy.owner.global.Constants;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.utils.GsonUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class WheelListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener{


    private static final int SORT_GENERAL = 0;
    private static final int SORT_PRICE = 1;
    private static final int SORT_FILTER = 2;
    private static final String TAG = "WheelListActivity";
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.tv_rank_general)
    TextView tvRankGeneral;
    @BindView(R.id.iv_rank_general)
    ImageView ivRankGeneral;
    @BindView(R.id.ll_rank_general)
    LinearLayout llRankGeneral;
    @BindView(R.id.tv_rank_by_price)
    TextView tvRankByPrice;
    @BindView(R.id.iv_rank_by_price)
    ImageView ivRankByPrice;
    @BindView(R.id.ll_rank_by_price)
    LinearLayout llRankByPrice;
    @BindView(R.id.tv_filter)
    TextView tvFilter;
    @BindView(R.id.iv_filter)
    ImageView ivFilter;
    @BindView(R.id.ll_filter)
    LinearLayout llFilter;
    @BindView(R.id.rv_wheel_list)
    EasyRecyclerView rvWheelList;

    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.nav_view)
    LinearLayout navigationView;

    private Context mContext;
    private Handler handler = new Handler();
    private WheelAttrFilterLayout wheelAttrFilterLayout;


    private int mCurrentSortType = 0;

    private WheelListAdapter mAdapter;

    private int specialModelId;
    private int page = 1;
    private String queryField = "salesDown";
    private String goodsBrandIds = "";
    private String minPrice = "";
    private String maxPrice = "";
    private SpecialGoodsAttrModel specialGoodsAttrModel;

    /***
     * 初始index 为-1  表示未设置
     */
    private int tmkIndex = -1;
    private int bpbIndex = -1;
    private int zjIndex = -1;

    private String  mFromTypeId;

    /**
     * 筛选项
     */

    List<WheelAttrKeyVal> otherAttrList ;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_wheel_list;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        mContext = this;
        specialModelId = getIntent().getIntExtra("special_mode_id",0);
        mFromTypeId = getIntent().getStringExtra("mFromTypeId");
        String title = getIntent().getStringExtra("special_mode_name");
        toolbarTitle.setText(""+title);
        if(title.equals("轮胎")) {
            toolbarSubtitle.setText("选择规格");
            toolbarSubtitle.setVisibility(View.VISIBLE);
        }else {
            toolbarSubtitle.setVisibility(View.GONE);
        }
        updateSortType(SORT_GENERAL);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
        wheelAttrFilterLayout = new WheelAttrFilterLayout(this);
        navigationView.addView(wheelAttrFilterLayout);

        wheelAttrFilterLayout.setCloseMenuCallBack(new WheelAttrFilterLayout.CloseMenuCallBack() {
            @Override
            public void setupCloseMean(String brandsId, String minPri, String maxPri, List<WheelAttrKeyVal> otherAttrs) {
                closeMenu();
                page = 1;
                goodsBrandIds = brandsId;
                maxPrice = maxPri;
                minPrice = minPri;
                otherAttrList = otherAttrs;
                getWheelListData(true);
            }
        });

        rvWheelList.setLayoutManager(new LinearLayoutManager(this));
        rvWheelList.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_gray_divider_decoration));
        mAdapter = new WheelListAdapter(this);
        rvWheelList.setAdapter(mAdapter);
        mAdapter.setMore(R.layout.view_more, this);
        mAdapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
                // adapter.resumeMore();
            }

            @Override
            public void onNoMoreClick() {
                mAdapter.resumeMore();
            }
        });

        mAdapter.setError(R.layout.view_error_net, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                mAdapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                mAdapter.resumeMore();

            }
        });

        mAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {
                Intent intent = new Intent(mContext, GoodsDetailActivity.class);
                intent.putExtra("goodsId", mAdapter.getAllData().get(position).getGoodsId());
                intent.putExtra("mFromType", Constants.GOODSSOURCE_PERFOR);
                intent.putExtra("mFromTypeId",  mFromTypeId);
                startActivity(intent);
            }
        });

        rvWheelList.setRefreshListener(this);

        getFilterData();
    }



    public void closeMenu() {
        InputMethodManager imm =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
        drawerLayout.closeDrawer(GravityCompat.END);
        wheelAttrFilterLayout.resetData();
    }

    public void openMenu() {
        drawerLayout.openDrawer(GravityCompat.END);
        if(wheelAttrFilterLayout.isNullData()) {
            wheelAttrFilterLayout.setData(specialGoodsAttrModel);
        }else {
            wheelAttrFilterLayout.setCopyData();
        }

    }

    @Override
    protected void updateViews() {

    }


    /**
     * 排序UI控制逻辑
     */
    private boolean generalDesc;//综合排序递减
    private boolean priceDesc;//价格递减
    private static final int REQUEST_WHEEL_ATTR_CODE = 111;

    @OnClick({R.id.toolbar_subtitle,R.id.ll_rank_general, R.id.ll_rank_by_price, R.id.ll_filter})
    protected void OnViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_subtitle:
                if(specialGoodsAttrModel != null) {
                    Intent intent = new Intent(WheelListActivity.this, ChooseWheelSpecActivity.class);
                    intent.putExtra("attributes_list", (Serializable) specialGoodsAttrModel.getAttributesList());
                    intent.putExtra("selected_tmk_index", tmkIndex);
                    intent.putExtra("selected_bpb_index", bpbIndex);
                    intent.putExtra("selected_zj_index", zjIndex);
                    WheelListActivity.this.startActivityForResult(intent,REQUEST_WHEEL_ATTR_CODE);
                }
                break;
            case R.id.ll_rank_general:
                updateSortType(SORT_GENERAL);
                break;
            case R.id.ll_rank_by_price:
                updateSortType(SORT_PRICE);
                break;
            case R.id.ll_filter:
//                updateSortType(SORT_FILTER);
                openMenu();
                break;
        }
    }

    /***
     * 选中的胎面宽，扁平比， 直径
     */
    private List<WheelAttrKeyVal> wheelAttrKeyValSelList = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode == REQUEST_WHEEL_ATTR_CODE){
                tmkIndex = data.getIntExtra("selected_tmk_index", tmkIndex);
                bpbIndex = data.getIntExtra("selected_bpb_index", bpbIndex);
                zjIndex = data.getIntExtra("selected_zj_index", zjIndex);
                MyLog.d("RAVEN","update tmkIndex = " + tmkIndex);
                MyLog.d("RAVEN","update bpbIndex = " + bpbIndex);
                MyLog.d("RAVEN","update zjIndex = " + zjIndex);
                dealSelectedWheelAttr();
                page = 1;
                rvWheelList.setRefreshing(true);
                getWheelListData(true);
            }
        }
    }

    /**处理选中的胎面宽 扁平比 直径*/
    private void dealSelectedWheelAttr(){
        wheelAttrKeyValSelList.clear();
        String rightTitle = "";
        for (int i = 0; i < specialGoodsAttrModel.getAttributesList().size(); ++i) {
            if (specialGoodsAttrModel.getAttributesList().get(i).getGoodsAttributesName().equals("胎面宽")) {
                MyLog.d("RAVEN","tmkIndex="+tmkIndex);
                //选择的值
                if(specialGoodsAttrModel.getAttributesList().get(i).getValues()!=null
                        &&specialGoodsAttrModel.getAttributesList().get(i).getValues().size() > tmkIndex) {
                    String val = specialGoodsAttrModel.getAttributesList().get(i).getValues().get(tmkIndex).getAttributesValue();
                    //属性id
                    int attrId = specialGoodsAttrModel.getAttributesList().get(i).getGoodsAttributesId();
                    wheelAttrKeyValSelList.add(new WheelAttrKeyVal(attrId, val));
                    rightTitle = rightTitle + specialGoodsAttrModel.getAttributesList().get(i).getValues().get(tmkIndex).getAttributesValue() + "/";
                }
            }
        }
        for (int i = 0; i < specialGoodsAttrModel.getAttributesList().size(); ++i) {
            if (specialGoodsAttrModel.getAttributesList().get(i).getGoodsAttributesName().equals("扁平比")) {
                if(specialGoodsAttrModel.getAttributesList().get(i).getValues()!=null
                        &&specialGoodsAttrModel.getAttributesList().get(i).getValues().size()>bpbIndex) {
                    String val = specialGoodsAttrModel.getAttributesList().get(i).getValues().get(bpbIndex).getAttributesValue();
                    int attrId = specialGoodsAttrModel.getAttributesList().get(i).getGoodsAttributesId();
                    wheelAttrKeyValSelList.add(new WheelAttrKeyVal(attrId, val));
                    rightTitle = rightTitle + specialGoodsAttrModel.getAttributesList().get(i).getValues().get(bpbIndex).getAttributesValue() + "R";
                }
            }

        }
        for (int i = 0; i < specialGoodsAttrModel.getAttributesList().size(); ++i) {
            if (specialGoodsAttrModel.getAttributesList().get(i).getGoodsAttributesName().equals("直径")) {
                if(specialGoodsAttrModel.getAttributesList().get(i).getValues()!=null
                        &&specialGoodsAttrModel.getAttributesList().get(i).getValues().size()>zjIndex) {
                    String val = specialGoodsAttrModel.getAttributesList().get(i).getValues().get(zjIndex).getAttributesValue();
                    int attrId = specialGoodsAttrModel.getAttributesList().get(i).getGoodsAttributesId();
                    wheelAttrKeyValSelList.add(new WheelAttrKeyVal(attrId, val));
                    rightTitle = rightTitle + specialGoodsAttrModel.getAttributesList().get(i).getValues().get(zjIndex).getAttributesValue();
                }
            }
        }

        toolbarSubtitle.setText(""+rightTitle);

    }

    private void updateSortType(int type) {

        if (type == SORT_GENERAL) {

            tvRankGeneral.setEnabled(true);
            tvRankByPrice.setEnabled(false);
            tvFilter.setEnabled(false);
            ivRankByPrice.setImageResource(R.drawable.selector_arrow_normal);
            ivFilter.setEnabled(false);

            generalDesc = !generalDesc;

            ivRankGeneral.setImageResource(R.drawable.selector_arrow_selected);//enable为true表示递减
            ivRankGeneral.setEnabled(generalDesc);
            if(generalDesc){
                queryField = "salesDown";
            }else{
                queryField = "salesUp";
            }

        } else if (type == SORT_PRICE) {

            tvRankGeneral.setEnabled(false);
            tvRankByPrice.setEnabled(true);
            tvFilter.setEnabled(false);
            ivRankGeneral.setImageResource(R.drawable.selector_arrow_normal);
            ivFilter.setEnabled(false);

            priceDesc = !priceDesc;
            ivRankByPrice.setImageResource(R.drawable.selector_arrow_selected);
            ivRankByPrice.setEnabled(priceDesc);
            if(priceDesc){
                queryField = "priceDown";
            }else{
                queryField = "priceUp";
            }

        } else if (type == SORT_FILTER) {
            tvRankGeneral.setEnabled(false);
            tvRankByPrice.setEnabled(false);
            tvFilter.setEnabled(true);
            ivFilter.setEnabled(true);
            ivRankGeneral.setImageResource(R.drawable.selector_arrow_normal);
            ivRankByPrice.setImageResource(R.drawable.selector_arrow_normal);

        }
        page = 1;
        getWheelListData(true);
    }

    private void getFilterData(){
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_SPECIAL_MODEL_GOODS_ATTR);
        if( UserHelper.getInstance().getSessionInfoModel(mContext) != null
                && !TextUtils.isEmpty(UserHelper.getInstance().getSessionInfoModel(mContext).getSession())) {
            params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(mContext).getSession());
        }
        params.addBodyParameter("specialModelId", ""+specialModelId);
        MyLog.d(TAG,"params = "+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(WheelListActivity.this, result);
                if(data != null){
                    MyLog.d(TAG, "data = " + data);
                    specialGoodsAttrModel =  GsonUtils.fromJson(data, SpecialGoodsAttrModel.class);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void getWheelListData(final boolean isfirst){
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_SPECIAL_MODEL_GOODS_LIST);
        if( UserHelper.getInstance().getSessionInfoModel(mContext) != null
                && !TextUtils.isEmpty(UserHelper.getInstance().getSessionInfoModel(mContext).getSession())) {
            params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(mContext).getSession());
            String bindStoreId = SharedPreferencesUtils.getParam(mContext, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "";
            params.addBodyParameter("storeId", bindStoreId);
        }
        params.addBodyParameter("specialModelId", ""+specialModelId);
        params.addBodyParameter("page", ""+page);
        params.addBodyParameter("size", "10");
        params.addBodyParameter("queryField", queryField);
        if(!TextUtils.isEmpty(goodsBrandIds)) {
            params.addBodyParameter("goodsBrandIds", goodsBrandIds);
        }

        if(!TextUtils.isEmpty(minPrice)) {
            params.addBodyParameter("minPrice", minPrice);
        }

        if(!TextUtils.isEmpty(maxPrice)) {
            params.addBodyParameter("maxPrice", maxPrice);
        }

        /**轮胎 直径 扁平比之类*/
        if(wheelAttrKeyValSelList!=null && wheelAttrKeyValSelList.size() > 0){

            for(WheelAttrKeyVal keyVal : wheelAttrKeyValSelList) {
                params.addBodyParameter("attr_" + keyVal.getAttrId(), keyVal.getAttrVal());
            }
        }


        if(otherAttrList != null && otherAttrList.size()>0){
            for(WheelAttrKeyVal keyVal : otherAttrList) {
                params.addBodyParameter("attr_" + keyVal.getAttrId(), keyVal.getAttrVal());
            }
        }


        MyLog.d(TAG,"params = "+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(WheelListActivity.this, result);
                if(data != null){
                    MyLog.d(TAG, "data = " + data);
                    SpecialGoodsModel specialGoodsModel =  GsonUtils.fromJson(data, SpecialGoodsModel.class);
                    if(specialGoodsModel!=null && specialGoodsModel.getList() != null){
                        if (isfirst) {
                            mAdapter.clear();
                        }
                        if (specialGoodsModel.getList().size() < 9) {
                            mAdapter.stopMore();
                        }
                        mAdapter.addAll(specialGoodsModel.getList());
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(WheelListActivity.this)) {
                    mAdapter.pauseMore();
                    rvWheelList.showError();
                    return;
                }
                page++;
                getWheelListData(false);

            }
        }, 1000);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mAdapter.clear();
                page = 1;
                getWheelListData(true);
                getFilterData();
            }
        }, 1000);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(drawerLayout!=null&& drawerLayout.isDrawerOpen(GravityCompat.END)){
                closeMenu();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
